<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Intervention\Image\ImageManagerStatic as Image;

class UploadController extends Controller
{
    /**
    * 文件上传
    */
   public function uploadFile(Request $request) {
        $file = $request->file('file');
        // 此时 $this->upload如果成功就返回文件名不成功返回false
        $data = [
            'err'   => 1,
            'msg'       => '上传失败!',
            'file_path' => ''
        ];
        $fileName = $this->upload($file);
        if ($fileName) {
            $data['file_path'] = url($fileName);
            $data['msg']       = "上传成功!";
            $data['err']   = 0;
        }
        return $data;
    }

    /**
     * 验证文件是否合法
     */
    public function upload($file, $disk='public') {
        // 1.是否上传成功
        if (! $file->isValid()) {
        return false;
        }

        // 2.是否符合文件类型 getClientOriginalExtension 获得文件后缀名
        $fileExtension = $file->getClientOriginalExtension();
        if(! in_array($fileExtension, ['png', 'jpg', 'gif'])) {
            return false;
        }

        // 3.判断大小是否符合 2M
        $tmpFile = $file->getRealPath();
        if (filesize($tmpFile) >= 2048000) {
            return false;
        }
        if( $tmpFile /*&& $filesize<300*1204*/){ //小于 300kb才去验证图片是否合法
            $app = \EasyWeChat\Factory::MiniProgram(config('wechat.mini_program.default'));
            $result = $app->content_security->checkImage($tmpFile);
            if($result['errcode']){ //返回错误
                return false;
            }
        }

        // 4.是否是通过http请求表单提交的文件
        if (! is_uploaded_file($tmpFile)) {
            return false;
        }

        // 5.每天一个文件夹,分开存储, 生成一个随机文件名
        $fileName = date('Ymd').'/'.md5(time()) .mt_rand(0,9999).'.'. $fileExtension;
        if (\Storage::disk($disk)->put($fileName, file_get_contents($tmpFile)) ){
            return \Storage::url($fileName);
        }
    }
    
}
